<?php

class spAddToListComboTextText extends spAddToListBase
{
	private $data;

	public function __construct( $data=null )
	{
		$this->data = $data;
		parent::__construct( $data );
		parent::setClass( "spAddToListBase spAddToListComboTextText" );
	}
	
	protected function createInsertHtml( $param=array() )
	{
		$data = $this->data;
		
		$selected_value = isset($param["selected_value"])?$param["selected_value"]:"";
		
		$name 		= isset($data["name"])?$data["name"]:"";
		$title 		= isset($param["title"])?$param["title"]:"";
		$data_info	= isset($param["data_info"])?$param["data_info"]:"";
		
		// FIXME: remove wordpress code and find a way to create the path to the image
		$img = get_option('home').'/wp-content/plugins/gym/sigmaphp/html/extended/dragbar_gray.png';
		$i = new spImage(array("src"=>$img));
		$i->addAttr( "align", "top" );
		
		$combobox = new spCombobox( array( 
			"name"			 => $data["name"]."_field[]", 
			"list"			 => $data["list"],
			"selected_value" => $selected_value 
		));

		$table = new spTableExt;
		$table->addRowChilds( array(
			$i,
			$combobox,
			new spInputText( array( "name"=>$name."_title[]", 		"value"=>$title ) ),
			new spInputText( array( "name"=>$name."_data_info[]", 	"value"=>$data_info ) )
		));

		return $table;		
	}	
	
	public function setElementDataString( $s )
	{
		parent::setElementDataString( $s );

		$insert_here = $this->find("insert_here");
		
		$obj = json_decode( $s, true );
		foreach ( $obj as $o )
		{
			$insert_here->addChild( $this->createCloneableContainer( array(
					"selected_value"	=> $o["field"],
					"title"				=> $o["title"],
					"data_info"			=> $o["data_info"]
				)));
		}
	}
	
	public function updateFromRequest()
	{
		parent::updateFromRequest();

		// convience variables
		$data = $this->data;
		$r = $_REQUEST;	
		
		$name = isset($data["name"])?$data["name"]:"";

		if ( isset($r[$name."_field"]) )
		{
			$arField = array_slice( $r[$name."_field"], 1 );			// remove first element in array (the clonable object)
			$arTitle = array_slice( $r[$name."_title"], 1 );			// remove first element in array (the clonable object)
			$arDataInfo = array_slice( $r[$name."_data_info"], 1 );		// remove first element in array (the clonable object)
			
			$field = current( $arField );
			$title = current( $arTitle );
			$data_info = current( $arDataInfo );
		
			$obj = array();
			while ( $field!==FALSE )
			{
				$obj[] = array( "field"=>$field, "title"=>$title, "data_info"=>$data_info );
		
				$field = next( $arField );
				$title = next( $arTitle );
				$data_info = next( $arDataInfo );
			}

			$this->setElementDataString( json_encode( $obj ) );
		}
	}
	
}

?>